package com.ujs.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ujs.commonutils.utils.JwtUtils;
import com.ujs.order.entity.TOrder;
import com.ujs.order.feign.CourseFeignService;
import com.ujs.order.feign.UcenterFeignService;
import com.ujs.order.mapper.TOrderMapper;
import com.ujs.order.service.TOrderService;
import com.ujs.order.utils.OrderNoUtils;
import com.ujs.servicebase.entity.CourseVoOrder;
import com.ujs.servicebase.entity.MemberVoOrder;
import com.ujs.servicebase.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-09-03
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {
    @Autowired
    private UcenterFeignService ucenterFeignService;
    @Autowired
    private CourseFeignService courseFeignService;

    @Override
    public String saveOrder(String courseId, String memberId) {
        // 查询用户基本信息
        MemberVoOrder memberInfoById = ucenterFeignService.getMemberInfoById(memberId);
        if (memberInfoById == null) {
            throw new GuliException(20001, "获取用户信息出错");
        }
        // 查询课程基本信息
        CourseVoOrder courseInfo = courseFeignService.getCourseInfoById(courseId);
        // 设置订单信息
        TOrder order = new TOrder();
        BeanUtils.copyProperties(memberInfoById, order);
        BeanUtils.copyProperties(courseInfo, order);
        order.setTotalFee(courseInfo.getPrice());
        order.setMemberId(memberId);
        order.setStatus(0);
        order.setPayType(1);
        String orderSn = OrderNoUtils.getOrderNo();
        order.setOrderNo(orderSn);
        baseMapper.insert(order);
        System.out.println("order===>" + order);
        return orderSn;
    }

    @Override
    public TOrder getOrderInfo(String orderno) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<TOrder>().eq("order_no", orderno);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Boolean isBuyCourse(String courseId, String memberId) {
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("status", 1);
        return baseMapper.selectCount(queryWrapper) > 0;
    }
}
